import 'package:casdon/modules/lifeCircle/data/model/life_subject_module.dart';
import 'package:casdon/modules/lifeCircle/data/model/life_topic_module.dart';
import 'package:casdon/modules/lifeCircle/domain/states/life_subject_list_state.dart';
import 'package:casdon/modules/lifeCircle/providers/life_provider.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

// 获取生活圈各个板块， type = 1： 致敬生活家，type = 0: 其他板块如，生活家，食物等
class LifeSubjectListNotifier
    extends AutoDisposeFamilyAsyncNotifier<LifeSubjectListState, int> {
  final int pageSize = 10;
  late final int type; //.0-用户；1-官方(官方帖子，横向列表展示，最多5条，所以首页不需要提供加载更多)
  bool _isRefreshing = false;

  @override
  Future<LifeSubjectListState> build(int type) async {
    this.type = type;
    final cached = state.valueOrNull;
    if (cached != null && cached.data.isNotEmpty) {
      Future.microtask(_refreshSilently);
      return cached;
    }
    return _fetchData(type);
  }

  Future<void> refresh() async {
    await _refreshSilently(force: true);
  }

  Future<void> loadMore() async {
    final current = state.valueOrNull;
    if (current == null) return;

    // 检查是否有任何 subject 还有更多数据可以加载
    bool hasMoreData = false;
    for (var subjectState in current.data) {
      final currentTopicCount = subjectState.topicList?.length ?? 0;
      if (currentTopicCount < subjectState.totalSize) {
        hasMoreData = true;
        break;
      }
    }

    if (!hasMoreData) return;

    // 为每个还有更多数据的 subject 加载下一页
    final updatedData = <LifeSubjectState>[];
    for (var subjectState in current.data) {
      final currentTopicCount = subjectState.topicList?.length ?? 0;
      if (currentTopicCount < subjectState.totalSize) {
        // 计算下一页
        final nextPage = subjectState.pageNum + 1;
        try {
          final topicRet = await ref
              .read(lifeTopicListUsecaseProvider)
              .execute(
                id: subjectState.lifeSubject!.id,
                pageNum: nextPage,
                pageSize: pageSize,
              );

          if (topicRet.rows != null && topicRet.rows!.isNotEmpty) {
            // 追加新数据到现有列表
            final newTopics = LifeTopicModule.listFromApi(topicRet.rows!);
            final updatedTopicList = <LifeTopicModule>[
              ...(subjectState.topicList ?? []),
              ...newTopics,
            ];

            updatedData.add(
              subjectState.copyWith(
                topicList: updatedTopicList,
                pageNum: nextPage,
                totalSize: topicRet.total,
              ),
            );
          } else {
            // 没有更多数据，保持原样
            updatedData.add(subjectState);
          }
        } catch (e) {
          // 加载失败，保持原样
          updatedData.add(subjectState);
        }
      } else {
        // 没有更多数据，保持原样
        updatedData.add(subjectState);
      }
    }

    state = AsyncValue.data(
      LifeSubjectListState(
        data: updatedData,
        currentIndex: current.currentIndex,
      ),
    );
  }

  Future<void> _refreshSilently({bool force = false}) async {
    if (_isRefreshing) return;
    _isRefreshing = true;
    final previous = state.valueOrNull;
    try {
      final newState = await _fetchData(type);

      state = AsyncValue.data(newState);
    } catch (e, st) {
      if (previous == null) {
        state = AsyncValue.error(e, st);
      } else if (force) {
        state = AsyncValue.data(previous);
      }
    } finally {
      _isRefreshing = false;
    }
  }

  Future<LifeSubjectListState> _fetchData(int type) async {
    final ret = await ref
        .read(lifeSujectListUsecaseProvider)
        .execute(type: type);

    if (ret.isEmpty) {
      return LifeSubjectListState.initial();
    }

    final List<LifeSubjectState> subjectStates = [];

    for (final e in ret) {
      final baseState = LifeSubjectState(
        lifeSubject: LifeSubjectModule.fromApi(e),
        topicList: [],
        pageNum: 0,
        totalSize: 0,
      );
      LifeSubjectState subjectState = baseState;
      // 获取 每个话题下的帖子列表
      final topicRet = await ref
          .read(lifeTopicListUsecaseProvider)
          .execute(
            id: baseState.lifeSubject!.id,
            pageNum: 1,
            pageSize: pageSize,
          );
      if (topicRet.rows != null && topicRet.rows!.isNotEmpty) {
        subjectState = subjectState.copyWith(
          topicList: LifeTopicModule.listFromApi(topicRet.rows!),
          pageNum: 1, // 设置为1，因为已经加载了第1页
          totalSize: topicRet.total,
        );
      } else {
        subjectState = subjectState.copyWith(
          topicList: [],
          pageNum: 0,
          totalSize: topicRet.total,
        );
      }

      subjectStates.add(subjectState);
    }

    return LifeSubjectListState(data: subjectStates);
  }
}

final lifeSubjectListNotifierProvider =
    AutoDisposeAsyncNotifierProviderFamily<
      LifeSubjectListNotifier,
      LifeSubjectListState,
      int
    >(LifeSubjectListNotifier.new);
